package com.nwpu.bigdata.service.impl;

import java.util.ArrayList;
import java.util.List;
import org.influxdb.dto.QueryResult;
import org.influxdb.dto.QueryResult.Result;
import org.influxdb.dto.QueryResult.Series;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.ImportResource;
import org.springframework.stereotype.Service;

import com.nwpu.bigdata.dto.Common;
import com.nwpu.bigdata.service.StorageService;
import com.nwpu.bigdata.util.impl.InfluxDBUtilImpl;
import com.nwpu.bigdata.util.impl.InfluxdbService;




/**
 *@version:2018年6月5日下午8:42:37
*/
/**
 * @author Administrator
 *
 */
@Service
@ImportResource(locations= {"classpath:/xmlConfig/spring/applicationContext-util.xml"})
public class StorageServiceImpl implements StorageService{
	
	@Autowired
	private InfluxDBUtilImpl influDBClient;
	
	@Value("${retentionPolicy.cluster}")
	private String retentionPolicy;
	
	@Value("${inluxdb.k8s}")
	private String dbname;
	@Override
    public List<Common> storageFree(){

		
	    InfluxdbService service = new InfluxdbService(dbname,retentionPolicy,influDBClient.builder());
	    if(service.equals(null))
	    {
	    	return null;
	    }
	    //执行查询文件系统限制表的数据   
	    QueryResult queryResultLimit = service.query("SELECT mean(value) FROM \"filesystem/limit\" WHERE time >= now() - 22m and resource_id = '/dev/vda1' group by nodename,time(2m)");//查询的某个指标
	    
	    System.out.println(queryResultLimit+"每个节点的限制量");
	    //查询文件系统使用表的数据
	    QueryResult queryResultUsage = service.query("SELECT mean(value) FROM \"filesystem/usage\" WHERE time >= now() - 22m and resource_id = '/dev/vda1' group by nodename,time(2m)");//查询的某个指标
	    
	    System.out.println(queryResultUsage+"每个节点的已使用量量");
	    //当查询结果为空时返回空
	    if(queryResultLimit.getResults() == null &&  queryResultUsage.getResults() == null) {
			System.out.println("the result is empty, end query!");
			return null; 
		}
	    //创建列表用于存放查询结果中的数据
	    List<Common> limitList = new ArrayList<Common>();
	    List<Common> usageList = new ArrayList<Common>();
	    List<Common> freeList = new ArrayList<Common>();
	    //遍历Limit查询结果，下面两个遍历可以写成一个方法
		for(Result result : queryResultLimit.getResults()){
			
			List<Series> series = result.getSeries();
			if(series == null){
				return null;
			}
			
			for(Series serie : series) {
			
				Common common = new Common();
				
				List<Double> values = new ArrayList<Double>();
				//得到查询结果中节点名称
				String nodename = serie.getTags().get("nodename");

				List<List<Object>> listSerie = serie.getValues();	
				//遍历查询结果中的values
				common.setNodename(nodename);
				for(int i = 0; i < listSerie.size(); i++){//将数据放到一个list中
					if(i == 0 || i == (listSerie.size()-1)){
						
					}else if(listSerie.get(i).get(0) == null){
						values.add((i-1), 0.0);
					}
					else{
						values.add((i-1), (Double) listSerie.get(i).get(1));
					}
					
				}
				common.setValues(values);
				limitList.add(common);
				
			}
			
			
		}
		//同上
        for(Result result : queryResultUsage.getResults()){
			
			List<Series> series = result.getSeries();
			if(series == null){
				return null;
			}
			for(Series serie : series) {
				Common common = new Common();
				List<Double> values = new ArrayList<Double>();
				String nodename = serie.getTags().get("nodename");
				System.out.println(serie);
				System.out.println("节点名为："+nodename);
				List<List<Object>> listSerie = serie.getValues();				
				common.setNodename(nodename);
				for(int i = 0; i < listSerie.size(); i++){//将数据放到一个list中
				
					if(i == 0 || i == (listSerie.size()-1)){
						
					}else if(listSerie.get(i).get(0) == null){
						values.add((i-1), 0.0);
					}
					else{
						values.add((i-1), (Double) listSerie.get(i).get(1));
					}
				}
				common.setValues(values);
				usageList.add(common);
			}
			
			
		}
        //将遍历结果进行相减得到文件系统的可用空间，并进行单位转换
        for(int i = 0; i < usageList.size(); i++){
        	List<Double> values = new ArrayList<Double>();
        	Common common = new Common();
			String nodename = limitList.get(i).getNodename();
			
			System.out.println("#########"+usageList.get(i).getValues());
			for(int j = 0; j <10; j++){
				double freeValue = (limitList.get(i).getValues().get(j) - usageList.get(i).getValues().get(j))/(1024 * 1024 * 1024);
				values.add(j, freeValue);
			}
			
			
			common.setNodename(nodename);
			common.setValues(values);
			freeList.add(common);
		}
        
        influDBClient.builder().close();
	    return freeList;
	}
	
}
